<?php
namespace app\common\component\admin;

class AdminValidate extends \think\Validate {
	public function common() {
		$this -> rule([
			'admin_name' => 'require',
			'password' => 'require|min:6'
		]);

		$this -> message([
			'admin_name.require' => '账号必须填写',
			'password.require' => '密码必须填写',
			'password.min' => '密码必须大于六位'
		]);
	}
	
	public function create($data) {
		$this -> common();

		$this -> rule([
			'comfirm_password' => 'require|confirm:password'
		]);

		$this -> message([
			'comfirm_password.require' => '确认密码必须填写',
			'comfirm_password.confirm' => '密码与确认密码不一致'
		]);

		if($this -> check($data)) {
			if(AdminModel::get(['admin_name' => $data['admin_name']])) {
	    		return [
					'code' => -1,
					'message' => '此账号:' . $data['admin_name'] . '已被注册!'
				];
	    }

    		return [
    			'code' => 0,
    			'message' => 'Success'
    		];
    	}
    	return [
			'code' => -1,
			'message' => $this -> getError()
		];
	}

	public function login($data) {
		$this -> common();

		$this -> rule([
			'captcha' => 'require|captcha'
		]);

		$this -> message([
			'captcha.require' => '验证码必须填写'
		]);

    	return $this -> checkData($data);
	}

	public function checkPassword($data) {
		$this -> rule([
			'old_password' => 'require|min:6',
			'new_password' => 'require|min:6',
			'new_confirm_password' => 'require|min:6|confirm:new_password'
		]);

		$this -> message([
			'old_password.require' => '原密码必须填写',
			'old_password.min' => '原密码必须大于六位',
			'new_password.require' => '新密码必须填写',
			'new_password.min' => '新密码必须大于六位',
			'new_confirm_password.require' => '新确认密码必须填写',
			'new_confirm_password.min' => '新确认密码必须大于六位',
			'new_confirm_password.confirm' => '新密码与新确认密码不一致'
		]);

		$resultCheck = $this -> checkData($data);
		if($resultCheck['code'] === 0) {
			$getAdmin = (new AdminService) -> getAdmin();

			if(!checkPasswordHash($data['old_password'], $getAdmin['data']['admin'] -> password)) {
				return [
					'code' => -1,
					'message' => '原密码错误!'
				];
			}
		}

		return $resultCheck;
	}

	public function checkData($data) {
		if($this -> check($data)) {
    		return [
				'code' => 0,
				'message' => 'Success'
			];
    	}

    	return [
			'code' => -1,
			'message' => $this -> getError()
		];
	}
}
?>